package com.hsmw.api.config.jwt;

import com.alibaba.fastjson.JSONObject;
import com.hsmw.common.context.SecurityConstants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;


import javax.crypto.SecretKey;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author shuang.kou
 * @description JWT工具类
 */
public class JwtTokenUtils {


	/**
	 * 生成足够的安全随机密钥，以适合符合规范的签名
	 */
	private static final SecretKey SECRET_KEY = Keys.hmacShaKeyFor(SecurityConstants.JWT_SECRET_KEY.getBytes());

	public static String createToken(String username, String id, List<String> roles, boolean isRememberMe) {
		long expiration = isRememberMe ? SecurityConstants.EXPIRATION_REMEMBER : SecurityConstants.EXPIRATION;
		final Date createdDate = new Date();
		final Date expirationDate = new Date(createdDate.getTime() + expiration * 1000);
		String tokenPrefix = Jwts.builder()
				.claim(SecurityConstants.ROLE_CLAIMS, String.join(",", roles))
				.setHeaderParam("type", SecurityConstants.TOKEN_TYPE)
				.signWith(SignatureAlgorithm.HS256, SECRET_KEY)
				.setId(id)
				.setIssuer("SnailClimb")
				.setIssuedAt(createdDate)
				.setSubject(username)
				.setExpiration(expirationDate)
				.compact();
		/**
		 * 添加 token 前缀 "Bearer "
		 */
		return SecurityConstants.TOKEN_PREFIX + tokenPrefix;
	}

	public static String getId(String token) {
		Claims claims = getClaims(token);
		return claims.getId();
	}

	private static Claims getClaims(String token) {
		return Jwts.parser()
				.setSigningKey(SECRET_KEY)
				.parseClaimsJws(token)
				.getBody();
	}



}
